package com.google.code.tretris.network.connection;

import java.util.ArrayList;
import java.util.Collection;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import android.util.Log;

import com.google.code.tretris.network.exceptions.ConnectionFailedException;
import com.google.code.tretris.network.filter.TretrisPacketFilter;
import com.google.code.tretris.network.peers.NetworkClient;

public class TretrisXMPPConnection implements TretrisConnectionHandlerInterface{

	private XMPPConnection xmppConnection;
	private String host = "talk.google.com";
	private String port = "5222";
	
	
	public void disconnect() {
		xmppConnection.disconnect();
	}

	public void send(String message, String to) {
		Message mess = new Message(to);
		mess.setType(Message.Type.chat);
		mess.setBody(message);
		xmppConnection.sendPacket(mess);
	}


	public void broadcast(String message, Collection<NetworkClient> players) {
		for(NetworkClient e : players) {
			Message mess = new Message(e.getClientID());
			mess.setType(Message.Type.chat);
			mess.setBody(message);
			xmppConnection.sendPacket(mess);	
		}
	}

	Collection<RosterEntry> myRoster = null;

	
	public Collection<NetworkClient> connect(String user, String pass, PacketListener packetListener) throws ConnectionFailedException {

		String service = "gmail.com";
		String username = user;

		if (user.contains("@")) {
			service = user.split("@")[1].trim();
			username = user.split("@")[0].trim();
		}

		ConnectionConfiguration connConfig = new ConnectionConfiguration(host, Integer.parseInt(port), service);
		xmppConnection = new XMPPConnection(connConfig);

		try {
			xmppConnection.connect();
			xmppConnection.login(username, pass);

			myRoster = xmppConnection.getRoster().getEntries();

			TretrisPacketFilter filter = new TretrisPacketFilter();
			xmppConnection.addPacketListener(packetListener, filter);

		} catch (XMPPException e) {
			Log.e(this.getClass().toString(), e.getMessage());
			throw new ConnectionFailedException(e);
		}
		
		Collection<NetworkClient> networkClientRoster = new ArrayList<NetworkClient>();
		for(RosterEntry entry : myRoster) {
			networkClientRoster.add(new NetworkClient(entry.getUser(), entry.getName()));
		}
		
		return networkClientRoster;
	}
	
}
